/*
 * Copyright (C) 2012-2013  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.remote.rsa.message.data;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;

import org.osgi.framework.Bundle;

/**
 * Message : The message class.
 * 
 * <p>
 * Messages are used between remote RSAs to transport data (mainly remote calls
 * and responses).
 * </p>
 * 
 * @author Romain DUBOIS
 */
public class Message implements Serializable {

    /** Serial version */
    private static final long serialVersionUID = 1L;

    /**
     * Serialize an object.
     * 
     * @param pObject
     *            The object to serialize.
     * @return The serialization result
     * @throws IOException
     *             If a serialization error occurred
     */
    public static byte[] serialize(final Object pObject) throws IOException {
        final ByteArrayOutputStream lByteOut = new ByteArrayOutputStream();
        final ObjectOutputStream lOut = new ObjectOutputStream(lByteOut);
        lOut.writeObject(pObject);
        lOut.close();
        return lByteOut.toByteArray();
    }

    /**
     * Deserialize data using a sepcific bundle.
     * 
     * @param pData
     *            The data to deserialize
     * @param pBundle
     *            The bundle to use
     * @return The deserialized data
     * @throws IOException
     *             If a deserialization error occurred
     * @throws ClassNotFoundException
     *             If a serialized class is unknown in the provided bundle class
     *             space
     */
    public static Object deserialize(final byte[] pData, final Bundle pBundle) throws IOException,
            ClassNotFoundException {
        final ObjectInputStream lInput = new ObjectInputStream(new ByteArrayInputStream(pData)) {
            @Override
            protected Class<?> resolveClass(final ObjectStreamClass pDesc) throws IOException,
                    ClassNotFoundException {
                try {
                    return pBundle.loadClass(pDesc.getName());
                } catch (final ClassNotFoundException ex) {
                    return super.resolveClass(pDesc);
                }
            }
        };
        final Object lResult = lInput.readObject();
        lInput.close();
        return lResult;
    }

    /** The message ID */
    private long mId;
    /** The serialized data (for transport) */
    private byte[] mSerializedData;
    /** The non-standard sended data */
    private transient Object mData;

    /**
     * Constructor
     */
    public Message() {
        super();
    }

    /**
     * Constructor.
     * 
     * @param pData
     *            The data to send
     */
    public Message(final Object pData) {
        super();
        mData = pData;
    }

    /**
     * Constructor.
     * 
     * @param pSerializedData
     *            The sended data
     */
    public Message(final byte[] pSerializedData) {
        super();
        mSerializedData = pSerializedData;
    }

    /**
     * Constructor.
     * 
     * @param pId
     *            The message ID
     * @param pData
     *            The data to send
     */
    public Message(final long pId, final Object pData) {
        super();
        mId = pId;
        mData = pData;
    }

    /**
     * Constructor.
     * 
     * @param pId
     *            The message ID
     * @param pSerializedData
     *            The sended data
     */
    public Message(final long pId, final byte[] pSerializedData) {
        super();
        mId = pId;
        mSerializedData = pSerializedData;
    }

    /**
     * Get the message ID.
     * 
     * @return The message ID
     */
    public long getId() {
        return mId;
    }

    /**
     * Set the message ID.
     * 
     * @param pId
     *            The ID to set
     */
    public void setId(final long pId) {
        mId = pId;
    }

    /**
     * Retrieve the message data.
     * 
     * @param pBundle
     *            The bundle to use for deserialization
     * @return The message data
     * @throws ClassNotFoundException
     *             If a class of the result is not known in the bundle class
     *             space
     * @throws IOException
     *             If the deserialization failed
     */
    public Object getData(final Bundle pBundle) throws IOException, ClassNotFoundException {
        if (mData == null && mSerializedData != null) {
            mData = deserialize(mSerializedData, pBundle);
        }
        return mData;
    }

    /**
     * Serialize data for transport.
     * 
     * @throws IOException
     *             If serialization failed
     */
    public void prepareTransport() throws IOException {
        if (mData != null) {
            mSerializedData = serialize(mData);
        }
    }

    /**
     * {@inheritDoc}
     * 
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return getClass().getSimpleName() + '#' + String.valueOf(getId());
    }
}
